/**
 * 说明：http请求
 * 创建：雨中磐石  from www.rili123.cn
 * 时间：2014-11-28
 * 邮箱：qqqq2900@126.com
 * QQ：290802026/1073744729
 * */

package com.framerock.baselib;





import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public final class RockHttp{


	/**
	 * 取消http
	 * */
	private static HttpURLConnection httpConn = null;
	public static void httpcancel()
	{
		if(httpConn!=null)httpConn.disconnect();
		httpConn = null;
	}

	/**
	 * 访问
	 * */
	public static void sendurl(String url, String type, String params,CallBack call, int timeout){

		String ResultString = "";
		HttpURLConnection httpURLConnection = null;
		int httpcode = AA.HTTPB_ERROR;
		try{
			if(type.equals("GET")){
				if(!Rock.isEmpt(params)){
					String jg = Rock.contain(url, "?") ? "&":"?";
					url+=jg+params;
				}
			}
			URL requestUrl = new URL(url);
			//CLog.debug(url);
			httpURLConnection = (HttpURLConnection)requestUrl.openConnection();//打开连接
			httpURLConnection.setRequestMethod(type);//两种方法GET/POST
			httpURLConnection.setUseCaches(false); //不缓存
			if(type.equals("POST")){
				httpURLConnection.setDoOutput(true);
				byte[] data = params.getBytes();
				httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				httpURLConnection.setRequestProperty("Content-Length", data.length + "");
				OutputStream out = httpURLConnection.getOutputStream();
				out.write(data);
				out.flush();
				out.close();
			}
			httpURLConnection.setConnectTimeout(timeout);
			httpURLConnection.setReadTimeout(AA.HTTPG_SOTIMEOUT);
			httpURLConnection.connect();
			httpConn = httpURLConnection;

			int statusCode = httpURLConnection.getResponseCode();
			InputStream inputstream = httpURLConnection.getInputStream();
			String line = "";

			if(statusCode==200){
				httpcode = AA.HTTPB_SUCCESS;
			}else {
				if(statusCode==301)ResultString="地址被强制跳转";
			}
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
			int ci = 0;
			while ((line = reader.readLine()) != null) {
				if (ci > 0) ResultString += "\n";
				ResultString += line;
				ci++;
			}
			reader.close();
		}catch(MalformedURLException e){
			//CLog.debug(e.toString());
		} catch (ProtocolException e) {
			//CLog.debug(e.toString());
		} catch (IOException e) {
			ResultString = "无法访问网络";
			httpcode = AA.HTTPB_NOTWEN;
		} finally {
			if (httpURLConnection != null) httpURLConnection.disconnect();// 关闭连接
			httpConn = null;
		}
		
		if(call!=null)call.backhttp(httpcode, 0, ResultString);
	}

	public static void sendurl(String url, String type, String params,CallBack call){
		sendurl(url, type,params,call, 1000*30);
	}
}